// #ifndef VUE3
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
// #endif

// #ifdef VUE3
import { createStore } from 'vuex'
const store = createStore({
// #endif
	state: {
		userInfo: null, // 初始为 null
		stockRecords: [] // 股票记录列表
	},
	mutations: {
		// 设置用户信息
		setUserInfo(state, userInfo) {
			state.userInfo = userInfo
		},
		// 清空用户信息
		clearUserInfo(state) {
			state.userInfo = null
		},
		// 添加股票记录
		addStockRecord(state, record) {
			state.stockRecords.push(record);
		},
		// 更新股票记录
		updateStockRecord(state, { id, data }) {
			const index = state.stockRecords.findIndex(item => item.id === id);
			if (index !== -1) {
				state.stockRecords.splice(index, 1, { ...state.stockRecords[index], ...data });
			}
		}
	},
	actions: {
		// 登录后保存用户信息（同步到 Storage）
		login({ commit }, userInfo) {
			commit('setUserInfo', userInfo)
			uni.setStorageSync('userInfo', userInfo) // 持久化到 Storage
		},
		// 登出（清空 store 和 Storage）
		logout({ commit }) {
			commit('clearUserInfo')
			uni.removeStorageSync('userInfo')
		},
		// 初始化：从 Storage 读取用户信息到 store
		initUserInfo({ commit }) {
			const userInfo = uni.getStorageSync('userInfo')
			if (userInfo) {
				commit('setUserInfo', userInfo)
			}
		},
		// 保存股票记录
		saveStockRecord({ commit, state }, record) {
			// 生成唯一ID
			const newRecord = {
				id: Date.now().toString(),
				date: new Date().toLocaleDateString(),
				...record,
				buys: record.buys || [],
				sells: record.sells || []
			};
			commit('addStockRecord', newRecord);
			// 持久化到本地存储
			uni.setStorageSync('stockRecords', state.stockRecords);
			return newRecord;
		},
		// 获取股票记录列表
		fetchStockRecords({ commit, state }) {
			const records = uni.getStorageSync('stockRecords') || [];
			state.stockRecords = records;
			return records;
		},
		// 更新股票交易记录
		updateStockTrade({ commit, state }, { id, type, trade }) {
			const recordIndex = state.stockRecords.findIndex(item => item.id === id);
			if (recordIndex !== -1) {
				const updatedRecord = { ...state.stockRecords[recordIndex] };
				updatedRecord[type] = [...updatedRecord[type] || [], trade];
				commit('updateStockRecord', { id, data: updatedRecord });
				// 持久化到本地存储
				uni.setStorageSync('stockRecords', state.stockRecords);
			}
		}
	}
})

export default store

// 初始化时加载股票记录
store.dispatch('fetchStockRecords');
